package com.igoal.service;

import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Service;

@Service("contextService")
public class ApplicationContextService implements ApplicationContextAware {
	private final Log logger = LogFactory
			.getLog(ApplicationContextService.class);

	private ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public String getMessageProperties(String code) {
		return getMessageProperties(code, new Object[0]);
	}

	// TODO: get default locale
	public String getMessageProperties(String code, Object[] args) {
		// Locale locale = new Locale("vi", "VietNam");
		return getMessageProperties(code, args, Locale.US);
	}

	public String getMessageProperties(String code, Object[] args, Locale locale) {
		try {
			return applicationContext.getMessage(code, args, locale);
		} catch (NoSuchMessageException e) {
			logger.error("Cannot find message code: " + code, e);
			return null;
		}
	}
}
